package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 */
//加了RestController和Controller都会被处理
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody    //json数据
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 异常SQLIntegrityConstraintViolationException处理方法
     *
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        log.error(ex.getMessage());

        //处理name相同的情况
        if (ex.getMessage().contains("Duplicate entry")) {
            //获取已经存在的用户名，这里是从报错的异常信息中获取的
            String[] split = ex.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return R.error(msg);
        }

        //返回给前台的信息
        return R.error("未知错误");
    }

    /**
     * 异常处理方法  处理自定义的异常，为了让前端展示我们的异常信息，这里需要把异常进行全局捕获，然后返回给前端
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex){
        log.error(ex.getMessage());

        return R.error(ex.getMessage());
    }

}
